package com.rjwh.dingdong.client.activity.mathgame;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.image.ImageListBrowseActivity;
import com.rjwh.dingdong.client.activity.loginregist.ThirdPartyLoginActivity;
import com.rjwh.dingdong.client.adapter.DrawBookDetailCommentAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.DownloadInfo;
import com.rjwh.dingdong.client.bean.localbean.DrawBookCommentData;
import com.rjwh.dingdong.client.bean.localbean.LocalGmaeInfo;
import com.rjwh.dingdong.client.bean.localbean.MathBookDetailBanner;
import com.rjwh.dingdong.client.bean.localbean.MathGameBookDetailMathBook;
import com.rjwh.dingdong.client.bean.localbean.RadioPageBannerData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.download.DownloadManager;
import com.rjwh.dingdong.client.mvp.presenter.impl.MathGameDetailPresenter;
import com.rjwh.dingdong.client.mvp.view.MathGameDetailView;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.view.IndicatorHackyViewPager;
import com.rjwh.dingdong.client.view.NoScrollListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * @author Kay
 * @ClassName MathGameDetailActivity
 * @Description 游戏详情
 * @date 2016-8-29
 * @history 2016-8-29 author: description:
 */
public class MathGameDetailActivity extends BaseActivity implements MathGameDetailView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout testAppBarLayout;
    @BindView(R.id.download_manager_progressBar)
    ProgressBar downloadManagerProgressBar;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout_img)
    ImageView errorLayoutImg;
    @BindView(R.id.error_layout_text)
    TextView errorLayoutText;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.math_game_detail_top_viewpager)
    IndicatorHackyViewPager mathGameDetailTopViewpager;
    @BindView(R.id.math_game_detail_game_tab_catalog_root_rl)
    RelativeLayout mathGameDetailGameTabCatalogRootRl;
    @BindView(R.id.math_game_detail_game_tab_my_track_root_rl)
    RelativeLayout mathGameDetailGameTabMyTrackRootRl;
    @BindView(R.id.math_game_detail_comment_title_times_tv)
    TextView mathGameDetailCommentTitleTimesTv;
    @BindView(R.id.math_game_detail_comment_list_lv)
    NoScrollListView mathGameDetailCommentListLv;
    @BindView(R.id.math_game_detail_comment_all_btn)
    TextView mathGameDetailCommentAllBtn;
    @BindView(R.id.math_game_detail_scrowview)
    ScrollView mathGameDetailScrowview;
    @BindView(R.id.math_game_detail_progressBar)
    ProgressBar mathGameDetailProgressBar;
    @BindView(R.id.math_game_detail_bottom_root_rl)
    RelativeLayout mathGameDetailBottomRootRl;
    @BindView(R.id.math_game_detail_btn)
    Button mathGameDetailBtn;

    private int bookid;
    private DownloadInfo downloadInfo;
    private Observable<DownloadInfo> observable;
    private Observable<DownloadInfo> observableChange;
    private Observable<DownloadInfo> observableProg;
    private DrawBookDetailCommentAdapter commentAdapter;

    private MathGameDetailPresenter presenter;
    private List<MathBookDetailBanner> bannerlist;
    private MathGameBookDetailMathBook mathbook;
    private String gameUpdateVersion;
    private PlaybackService mPlayer;
    private MyPagerAdapter viewPagerAdapter;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.math_game_detail_layout);
        ButterKnife.bind(this);
        parseIntent();
        initView();
        startObserver();
        presenter = new MathGameDetailPresenter(this, this);
        presenter.subscribe();
        presenter.doGetMathBookDetail(bookid);
        initDownLoad();
    }

    public static void startActivity(Context context, String bookid) {
        Intent intent = new Intent(context, MathGameDetailActivity.class);
        intent.putExtra("bookid", bookid);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            bookid = Integer.parseInt(intent.getStringExtra("bookid"));
        }
    }

    private void initView() {
        initToolbarHelper();
        commentAdapter = new DrawBookDetailCommentAdapter(this, true);
        mathGameDetailCommentListLv.setFocusable(false);// 解决进入界面不定位到顶部
        mathGameDetailCommentListLv.setAdapter(commentAdapter);
        mathGameDetailCommentListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (MyApplication.spUtil.getBoolPreferenceByParamName(MathGameDetailActivity.this,
                        LocalConstant.SP_IS_LOGINED)) {
                    MathGameDetailCommentListActivity.startActivity(MathGameDetailActivity.this, bookid);
                } else {
                    ThirdPartyLoginActivity.startActivity(MathGameDetailActivity.this);
                }
            }
        });
        viewPagerAdapter = new MyPagerAdapter();
        mathGameDetailTopViewpager.setAdapter(viewPagerAdapter);
        mathGameDetailTopViewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        cancelTimer();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (viewPagerAdapter.getCount() > 2) {
                            startTimer();
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void initToolbarHelper() {
        toolbar.setTitle("");
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("");
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    private void startObserver() {
        observable = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_UNZIP, DownloadInfo.class);
        observableChange = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_CHANGE, DownloadInfo.class);
        observableProg = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_PROGRES, DownloadInfo.class);
        Subscriber subscriber = new Subscriber<DownloadInfo>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(DownloadInfo localGmaeInfo) {
                if (localGmaeInfo.getGameId() == bookid) {
                    if (localGmaeInfo.getDownloadState() == DownloadManager.STATE_UNZIP_SUCESS) {
                        mathGameDetailBtn.setText(R.string.start_game);
                    } else {
                        refreshState(localGmaeInfo);
                    }
                }
            }
        };
        Subscriber subscriberChange = new Subscriber<DownloadInfo>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(DownloadInfo localGmaeInfo) {
                if (localGmaeInfo.getGameId() == bookid) {
                    refreshState(localGmaeInfo);
                }
            }
        };
        Subscriber subscriberProg = new Subscriber<DownloadInfo>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(DownloadInfo localGmaeInfo) {
                if (localGmaeInfo.getGameId() == bookid) {
                    mathGameDetailProgressBar.setProgress((int) localGmaeInfo.getProgress());
                }
            }
        };
        addSubscription(observable, subscriber);
        addSubscription(observableChange, subscriberChange);
        addSubscription(observableProg, subscriberProg);

    }

    private void initDownLoad() {
        if (presenter.isGameNotNull(bookid)) {
            if (presenter.isGameUpdateIng(bookid)) {
                LogUtil.e("MathGameDetialActivity", "isUpdateing");
                if (downloadInfo != null) {
                    refreshState(downloadInfo);
                } else {
                    downloadInfo = DownloadManager.getInstance().getTaskByUrl(bookid);
                    refreshState(downloadInfo);
                }
            } else {
                initViewState(3);
            }
        } else {
            downloadInfo = DownloadManager.getInstance().getTaskByUrl(bookid);
            if (downloadInfo != null) {
                refreshState(downloadInfo);
            } else {
                initViewState(1);
            }
        }
    }

    public void initViewState(int type) {
        if (type == 3) {
            mathGameDetailBtn.setText(R.string.start_game);
        } else if (type == 1) {
            mathGameDetailBtn.setText(R.string.start_download);
        } else if (type == 2) {
            mathGameDetailBtn.setText(R.string.start_update);
        }
    }

    private void refreshState(DownloadInfo info) {
        downloadInfo = info;
        switch (info.getDownloadState()) {
            case DownloadManager.STATE_NONE:
                mathGameDetailBtn.setText(R.string.start_download);
                break;
            case DownloadManager.STATE_PAUSED:
                mathGameDetailBtn.setText(R.string.download_pause);
                mathGameDetailBtn.setBackgroundResource(R.drawable.transparent_btn_selector);
                mathGameDetailProgressBar.setProgress((int) info.getProgress());
                break;
            case DownloadManager.STATE_ERROR:
                mathGameDetailBtn.setText(R.string.download_fail);
                break;
            case DownloadManager.STATE_WAITING:
                mathGameDetailBtn.setText(R.string.download_wait);
                break;
            case DownloadManager.STATE_DOWNLOADING:
                mathGameDetailBtn.setText(R.string.download_downloading);
                mathGameDetailBtn.setBackgroundResource(R.drawable.transparent_btn_selector);
                mathGameDetailProgressBar.setProgress((int) info.getProgress());
                break;
            case DownloadManager.STATE_DOWNLOADED:
                mathGameDetailBtn.setText(R.string.download_finish);
                break;
            case DownloadManager.STATE_UNZIP:
                mathGameDetailBtn.setText(R.string.download_unziping);
                break;
            case DownloadManager.STATE_UNZIP_SUCESS:
                mathGameDetailBtn.setText(R.string.start_game);
                break;
            default:
                break;
        }


    }

    @Override
    public void loadData(List<MathBookDetailBanner> bannerlist, MathGameBookDetailMathBook mathbook, List<DrawBookCommentData> mathbookcommentlist) {
        this.mathbook = mathbook;
        String reply = mathbook.getReply();
        String version = mathbook.getVersion();
        String bookname = mathbook.getBookname();

        if (!bannerlist.isEmpty()) {
            this.bannerlist = bannerlist;
            //更新banner视图
            updataBannerView();
        }
        //更新标题栏
        if (getSupportActionBar() != null && bookname != null) {
            getSupportActionBar().setTitle(bookname);
        }
        //加载评论列表
        commentAdapter.clearAll();
        commentAdapter.appendToList(mathbookcommentlist);
        if (mathbookcommentlist.isEmpty()) {
            mathGameDetailCommentAllBtn.setVisibility(View.GONE);
        } else {
            mathGameDetailCommentAllBtn.setVisibility(View.VISIBLE);
        }
        //更新评论次数
        if (AsStrUtils.isEmpty(reply) || reply.equals("0")) {
            mathGameDetailCommentTitleTimesTv.setVisibility(View.GONE);
        } else {
            mathGameDetailCommentTitleTimesTv.setVisibility(View.VISIBLE);
            mathGameDetailCommentTitleTimesTv.setText(reply);
        }
        //版本比对
        if (!AsStrUtils.isEmpty(version)) {
            this.gameUpdateVersion = version;
        }

        checkUpdate();
    }


    private void checkUpdate() {

        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=2");

        if (!localGmaeInfoList.isEmpty()) {
            if (presenter.isGameUpdate(this.gameUpdateVersion, bookid)) {
                if (presenter.isGameUpdateIng(bookid)) {
                    if (downloadInfo != null) {
                        refreshState(downloadInfo);
                    }
                } else {
                    LocalGmaeInfo localGmaeInfo = localGmaeInfoList.get(0);
                    showUpdateDialog(localGmaeInfo);
                }
            }
        }

    }

    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    private void updataBannerView() {
        if (time == null) {
            time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
        }
        viewPagerAdapter.addList(bannerlist);
        startTimer();
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (viewPagerAdapter == null) {
                return;
            }
            int count = viewPagerAdapter.getCount();
            if (count > 2) { // 多于2个，才循环
                int index = mathGameDetailTopViewpager.getCurrentItem();
                index = (index + 1) % count;
                mathGameDetailTopViewpager.setCurrentItem(index, true);
                time.start();
            } else {
                time.cancel();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    public class MyPagerAdapter extends PagerAdapter {

        private List<MathBookDetailBanner> bannerlist = new ArrayList<>();

        public void addList(List<MathBookDetailBanner> list) {
            if (list != null) {
                bannerlist.clear();
                bannerlist.addAll(list);
                notifyDataSetChanged();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (bannerlist.get(position).getBannerurl() != null) {
                Glide.with(MathGameDetailActivity.this).load(bannerlist.get(position).getBannerurl()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ArrayList<String> listImage = new ArrayList<>();
                        for (MathBookDetailBanner mathBookDetailBanner : bannerlist) {
                            listImage.add(mathBookDetailBanner.getBannerurl());
                        }
                        Intent intentBrowse = new Intent(MathGameDetailActivity.this, ImageListBrowseActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("list", listImage);
                        intentBrowse.putExtras(bundle);
                        intentBrowse.putExtra("position", position);
                        startActivity(intentBrowse);
                    }
                });
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return bannerlist == null ? 0 : bannerlist.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @OnClick({R.id.math_game_detail_comment_tab_input_btn, R.id.math_game_detail_comment_all_btn, R.id.math_game_detail_btn, R.id.math_game_detail_game_tab_catalog_root_rl, R.id.math_game_detail_game_tab_my_track_root_rl})
    public void onClick(View view) {
        if (MyApplication.spUtil.getBoolPreferenceByParamName(this, LocalConstant.SP_IS_LOGINED)) {
            switch (view.getId()) {
                case R.id.math_game_detail_comment_tab_input_btn:
                    // 跳转到输入评论
                    Intent intent = new Intent(MathGameDetailActivity.this, MathGameDetailCommentInputActivity.class);
                    intent.putExtra("bookid", bookid);
                    intent.putExtra("tag", 2);
                    startActivity(intent);
                    break;
                case R.id.math_game_detail_comment_all_btn:
                    // 跳转到评论列表
                    MathGameDetailCommentListActivity.startActivity(MathGameDetailActivity.this, bookid);
                    break;
                case R.id.math_game_detail_btn:
                    List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=2");
                    if (!localGmaeInfoList.isEmpty()) {
                        if (presenter.isGameUpdateIng(bookid)) {
                            doDownLoad();
                        } else {
                            //启动游戏
                            presenter.startGame(bookid, mPlayer);
                        }
                    } else {
                        // 下载
                        doDownLoad();
                    }
                    break;
                case R.id.math_game_detail_game_tab_catalog_root_rl:
                    // 跳转到游戏目录
                    MathGameIslandsListActivity.startActivity(this, bookid, mathbook.getBookname(), "MathGameDetailActivity");
                    break;
                case R.id.math_game_detail_game_tab_my_track_root_rl:
                    // 跳转到我的足迹
                    MathGameMyTracksActivity.startActivity(this, String.valueOf(bookid), "MathGameDetailActivity");
                    break;
            }
        } else {
            ThirdPartyLoginActivity.startActivity(this);
        }
    }

    @OnClick(R.id.btn_refresh)
    public void onClick() {
        presenter.doGetMathBookDetail(bookid);
    }

    /**
     * 更新弹框
     */
    private void showUpdateDialog(final LocalGmaeInfo localGmaeInfo) {
        new AlertDialog.Builder(this)
                .setTitle("当前版本已经升级，赶紧更新以便获得更好的体验吧~")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        doUpdate(localGmaeInfo);
                    }
                })
                .show();
    }

    //更新
    private void doUpdate(LocalGmaeInfo mData) {
        //先删除旧版本
        MyApplication.db.delete(mData);

        doDownLoad();

        mData.setIsUpdate(2);
        MyApplication.db.update(mData);
    }

    private void doDownLoad() {
        presenter.doDownLoad(downloadInfo, mathbook, bookid);
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    private void stopObserver() {
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_UNZIP, observable);
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_CHANGE, observableChange);
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_PROGRES, observableProg);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onPause() {
        super.onPause();
        cancelTimer();
    }

    private void startTimer() {
        if (time != null) {
            time.start();
        }
    }

    private void cancelTimer() {
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        stopObserver();
        cancelTimer();
        time = null;
        super.onDestroy();
        presenter.detachView();
    }
}
